<template>
  <div class="user">
    <div class="tree menu-left">
      <div class="reload"><a><a-icon v-if="QX.read" @click="refreshOrgTree" type="reload" title="刷新组织机构列表"/></a></div>
      <div class="detail-title">组织机构</div>
      <a-tree :tree-data="treeData"
              show-icon
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :selectedKeys="selectedKeys"
              :replaceFields="{ key:'organizationId',title:'organizationName',value:'organizationId'}"
              @select="onSelect"
              @expand="onExpand"
      >
        <a-icon slot="company" type="home" theme="twoTone" />
        <a-icon slot="dept" type="flag" theme="twoTone" />
        <template #title="{ organizationName,children }">
          <a-icon v-if="children.length" type="apartment" style="color:#1890ff"/>
          <a-icon v-else type="team"  style="color:#1890ff"/>
          <TableTootip :content="organizationName"></TableTootip>
        </template>
      </a-tree>
    </div>
    <div class="user-list">
      <div class="search-title">查询条件</div>
      <div class="search-box">
        <a-form-model :model="searchForm" layout="inline" ref="searchForm" class="searchForm">
          <a-form-model-item prop="searchValue">
            <a-input v-model="searchForm.searchValue" placeholder="请输入用户账号/姓名/手机号">
              <a-icon slot="prefix" type="search"/>
            </a-input>
          </a-form-model-item>
          <a-form-model-item class="searchButton">
            <a-button type="primary" @click="getSearch" v-if="QX.read">查询</a-button>
            <a-button type="default" @click="restSearch('searchForm')" v-if="QX.read">重置</a-button>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div class="table-operation">
        <a-button type="primary" @click="addUsers" icon="plus" v-if="QX.add">批量新增</a-button>
        <a-button type="primary" @click="exportData" style="margin-left: 10px;">导出</a-button>
      </div>
      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="false"
        :loading="loading"
        :scroll="{x:1100,y: this.$getViewportSize().height-300 }"
        rowKey="userCode">
        <template
          v-for="col in columns"
          :slot="col.key"
          slot-scope="text,record"
        >
          <span v-if="col.key=='isLocked'">
            <a-switch v-model="record.isLocked === '1'" :disabled="!QX.edit || userCode === record.userCode" checked-children="启用" un-checked-children="禁用" @click="lockedClick(record)">
              <a-icon slot="checkedChildren" type="check" />
              <a-icon slot="unCheckedChildren" type="close" />
            </a-switch>
          </span>
          <span v-else-if="col.key=='isAdmin'">
            <a-tag  v-if="record.isAdmin === '0'">否</a-tag>
            <a-tag color="blue" v-else-if="record.isAdmin === '1'">是</a-tag>
          </span>
          <span v-else-if="col.key=='action'">
          <a @click="openCourseModal(record)" v-if="QX.read" ><a-icon class="iconBtn" type="ordered-list" />课程信息</a>
          <a-divider v-if="(QX.edit||QX.delete)" type="vertical"/>
          <a-dropdown v-if="(QX.edit||QX.delete)">
            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
              更多<a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item v-if="QX.edit&&record.userCode !== userCode">
                 <a @click="editUser(record)"><a-icon class="iconBtn" type="edit" />编辑</a>
              </a-menu-item>
              <a-menu-item v-if="QX.delete&&record.userCode !== userCode">
                <a-popconfirm
                  title="确认是否删除？"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="removeUser(record)"
                >
              <a href="#"><a-icon class="iconBtn" type="delete" />删除</a>
            </a-popconfirm>
              </a-menu-item>
  <a-menu-item v-if="QX.read">
    <a @click="openPkModal(record)"><a-icon class="iconBtn" type="team" />用户PK信息</a>
  </a-menu-item>


            </a-menu>
          </a-dropdown>
          </span>
          <span v-else>
            <TableTootip :content="text"></TableTootip>
          </span>
        </template>
      </a-table>
      <a-pagination
        show-size-changer
        :total="totalPage"
        :current="pageIndex"
        :pageSize="pageSize"
        @showSizeChange="onShowSizeChange"
        @change="onChangePage"
        style="float: right;margin-top: 15px"
      />
    </div>
<!--    编辑-->
    <a-drawer
      :closable="true"
      :title="title"
      :visible="visible"
      @close="visible=!visible"
      :width="1050"
    >
      <a-spin class="submitLoading" :spinning="submitLoading">
        <a-form-model :model="formEdit" :rules="rules"  ref="formEdit" :label-col="labelCol" :wrapper-col="wrapperCol" class="lay-drawer-form">
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="用户账号" prop="userCode">
                <a-input v-model="formEdit.userCode" :disabled="disabled" placeholder="请输入用户账号" :maxLength="20"/>
              </a-form-model-item>
              <a-form-model-item label="用户姓名" prop="userName">
                <a-input v-model="formEdit.userName" placeholder="请输入用户姓名" :maxLength="10"/>
              </a-form-model-item>
              <a-form-model-item label="手机号码" prop="mobilePhone">
                <a-input v-model="formEdit.mobilePhone" placeholder="请输入手机号码" :maxLength="11"/>
              </a-form-model-item>
              <a-form-model-item label="所在部门" prop="organizationId">
                <a-tree-select
                  v-model="formEdit.organizationId"
                  :treeData="treeData"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :replaceFields="{ key:'organizationId',title:'organizationName',value:'organizationId'}"
                  placeholder="请选择所在部门"
                  tree-default-expand-all
                  @change="onChange"
                >
                </a-tree-select>
              </a-form-model-item>
              <a-form-model-item label="账户状态" prop="isLocked">
                <a-radio-group v-model="formEdit.isLocked">
                  <a-radio value="1">启用</a-radio>
                  <a-radio value="0">禁用</a-radio>
                </a-radio-group>
              </a-form-model-item>
              <a-form-model-item label="管理员" prop="isAdmin" v-if="adminVisible">
                <a-radio-group v-model="formEdit.isAdmin">
                  <a-radio value="1">是</a-radio>
                  <a-radio value="0">否</a-radio>
                </a-radio-group>
              </a-form-model-item>

            </a-col>
            <a-col :span="12">
              <a-form-model-item label="工号" prop="jobNo">
                <a-input v-model="formEdit.jobNo" placeholder="请输入工号" :maxLength="20" disabled/>
              </a-form-model-item>
              <a-form-model-item label="选择角色" prop="userRole" :label-col="{span: 5}" :wrapper-col="{span: 17}">
                <a-select v-model="formEdit.userRole" :options="roleList" @change="onChangeRole" placeholder="请选择角色" style="width: 380px">
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="分配权限" prop="checkedKeys">
                <vue-scroll :ops="ops" style="height:350px;">
                  <a-tree
                    v-model="formEdit.checkedKeys"
                    checkable
                    @check="check"
                    :tree-data="roleAuthList"
                  />
                </vue-scroll>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <div
          :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '8px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }">
          <a-button
            type="default"
            @click="visible=!visible"
          >
            取消
          </a-button>
          <a-button
            type="primary"
            @click="submitForm"
          >
            确认
          </a-button>
        </div>
      </a-spin>
    </a-drawer>

    <a-modal centered="true" :footer="null" v-model="visibleKPI" :title="title" :width="1000"
             :bodyStyle="{ height: '450px', overflowY: 'auto', paddingBottom: '20px' }">
      <a-table
        :columns="columnsKPI"
        :data-source="kpiList"
        :pagination="false"
        :loading="loading"
        rowKey="id"
        :scroll="{y: this.$getViewportSize().height-280 }">
        <template
          v-for="col in columnsKPI"
          :slot="col.key"
          slot-scope="text,record"
        >
          <span>
          <TableTootip :content="text"></TableTootip>
        </span>
        </template>
      </a-table>
    </a-modal>

    <a-drawer :closable="true" :visible="visibleAdd" :title="title" :width="1050"
              @close="visibleAdd=!visibleAdd">
      <a-spin class="submitLoading" :spinning="submitAddLoading">
        <a-form-model :model="form" :rules="rules"  ref="form" :label-col="labelCol" :wrapper-col="wrapperCol">
          <div class="table-operation">
            <a-button type="primary" @click="addUser" icon="plus" v-if="QX.add">新增</a-button>
            <a-upload
              name="file"
              :action="uploadURL"
              :headers="headers"
              :before-upload="beforeUpload"
              @change="handleChangeUpload"
              :showUploadList="false"
              accept=".xls,.xlsx"
            >
              <a-button type="primary" icon="upload" v-if="QX.upload">导入</a-button>
            </a-upload>
          </div>
          <a-table
            class="addList"
          :columns="columnsAdd"
          :data-source="form.addList"
          :pagination="false"
          :loading="loading"
          rowKey="id"
          :scroll="{y: 320 }">
          <template
            v-for="col in columnsAdd"
            :slot="col.key"
            slot-scope="text,record,index"
          >
            <a-form-model-item v-if="col.key=='userCode'" :prop="'addList.' + index + '.'+col.key " :rules="{
                            required: true,
                            validator: validateUserCode,
                            trigger: 'blur',
                          }">
              <a-input
                style="margin: -5px 0"
                :value="text"
                @change="e => handleChange(e.target.value, record.id, col.key)"
              />
            </a-form-model-item>
            <a-form-model-item v-else-if="col.key=='mobilePhone'" :prop="'addList.' + index + '.'+col.key " :rules="{
                            required: true,
                            validator: validatePhone,
                            trigger: 'blur',
                          }">
              <a-input
                style="margin: -5px 0"
                :value="text"
                @change="e => handleChange(e.target.value, record.id, col.key)"
              />
            </a-form-model-item>
            <a-form-model-item v-else>
              <a-input
                style="margin: -5px 0"
                :value="text"
                @change="e => handleChange(e.target.value, record.id, col.key)"
              />
            </a-form-model-item>
          </template>
          <span slot="action" slot-scope="text,record,index">
          <a @click="() => del(record.id)">删除</a>
        </span>
        </a-table>
          <a-row style="margin-top: 20px;">
            <a-col :span="12">
              <a-form-model-item label="账户状态" prop="isLocked">
                <a-radio-group v-model="form.isLocked">
                  <a-radio value="1">启用</a-radio>
                  <a-radio value="0">禁用</a-radio>
                </a-radio-group>
              </a-form-model-item>
              <a-form-model-item label="管理员" prop="isAdmin" v-if="adminVisible">
                <a-radio-group v-model="form.isAdmin">
                  <a-radio value="1">是</a-radio>
                  <a-radio value="0">否</a-radio>
                </a-radio-group>
              </a-form-model-item>

            </a-col>
            <a-col :span="12">
              <a-form-model-item label="选择角色" prop="userRole" :label-col="{span: 5}" :wrapper-col="{span: 17}">
                <a-select v-model="form.userRole" :options="roleList" @change="onChangeRole" placeholder="请选择角色" style="width: 380px">
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="分配权限" prop="checkedKeys">
                <vue-scroll :ops="ops" style="height:350px;">
                  <a-tree
                    v-model="form.checkedKeys"
                    checkable
                    @check="check"
                    :tree-data="roleAuthList"
                  />
                </vue-scroll>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <div
          :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '8px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }">
          <a-button
            type="default"
            @click="visibleAdd=!visibleAdd"
          >
            取消
          </a-button>
          <a-popconfirm
            title="请检查数据是否正确？"
            ok-text="是"
            cancel-text="否"
            @confirm="submitFormAdd"
          >
            <a-button
              type="primary"
            >
              确认
            </a-button>
          </a-popconfirm>
        </div>
      </a-spin>
    </a-drawer>

    !-- 用户课程信息弹窗 -->
    <a-modal
      title="用户课程信息"
      :visible="visibleCourse"
      @cancel="visibleCourse = false"
      :footer="null"
      width="800px"
    >
      <a-table
        :columns="columnsCourse"
        :data-source="courseList"
        rowKey="id"
        :loading="loadingCourse"
        :pagination="false"
      >
      </a-table>
    </a-modal>
    <!-- 用户PK信息弹窗 -->
    <a-modal
      title="用户PK信息"
      :visible="visiblePk"
      @cancel="visiblePk = false"
      :footer="null"
      width="800px"
    >
      <a-table
        :columns="columnsPk"
        :data-source="pkList"
        rowKey="id"
        :loading="loadingPk"
        :pagination="false"
      >
      </a-table>
      <a-pagination
        style="margin-top: 10px; text-align: right;"
        :current="pkPageIndex"
        :total="pkTotalPage"
        :pageSize="pkPageSize"
        @change="onChangePkPage"
        @showSizeChange="onChangePkPage"
        show-size-changer
      />
    </a-modal>
  </div>
</template>

<script>
import { req,fileDownload } from '../../../api/axiosFun';
import preventBack from 'vue-prevent-browser-back';
import axios from 'axios';
import TableTootip from '../../../components/TableTootip.vue';

export default {
  name: 'User',
  mixins: [preventBack], // 注入
  components: {
    TableTootip,
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      const isMob = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/;
      if (!value) {
        callback(new Error('请输入手机号码'));
      } else if (!isMob.test(value)) {
        callback(new Error('手机号码格式错误'));
      }
      callback();
    };
    const validateUserCode = (rule, value, callback) => {
      const pattern = /^[A-Za-z0-9\-_\u4e00-\u9fa5]+$/;
      if (!value) {
        callback(new Error('请输入用户账号'));
      } else if (!pattern.test(value)) {
        callback(new Error('请输入字母数字、下划线_或中线-或中文'));
      }
      callback();
    };
    return {
      QX: {},
      adminVisible: false,
      disabled: false,
      labelCol: { span: 5 },
      wrapperCol: { span: 17 },
      userCode: this.$store.getters.userCode,
      rules: {
        userCode: [
          { required: true, validator: validateUserCode, trigger: 'blur' },
        ],
        userName: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
        ],
        mobilePhone: [
          { required: true, validator: validatePhone, trigger: 'blur' },
        ],
        isLocked: [
          { required: true, message: '请选择账户状态', trigger: 'change' },
        ],
        organizationId: [
          { required: true, message: '请选择所在部门', trigger: 'change' },
        ],
        userRole: [
          { required: true, message: '请选择角色', trigger: 'change' },
        ],
        isAdmin: [
          { required: true, message: '请选择是否是管理员', trigger: 'change' },
        ],
      },
      expandedKeys: [],
      autoExpandParent: true,
      roleList: [],
      roleAuthList: [],
      title: '',
      selectedKeys: [],
      companyDeptTree: [],
      form: {
        isLocked: '1',
        userRole: null,
        isAdmin: '0',
        selectAuth: [],
        checkedKeys: [],
        list: '',
        addList: [],
      },
      formEdit: {
        userCode: '',
        userName: '',
        jobNo: '',
        organizationId: undefined,
        mobilePhone: '',
        isLocked: '1',
        userRole: null,
        isAdmin: '0',
        selectAuth: [],
        checkedKeys: [],
      },
      searchForm: {
        searchValue: '',
        organizationId: '',
      },
      treeData: [],
      kpiList, // kpi考勤列表
      visible: false,
      visibleKPI: false,
      visibleAdd: false,
      dataList: [],
      columns: [],
      columnsKPI,
      columnsAdd,
      loading: false,
      submitLoading: false,
      submitAddLoading: false,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      ops: {
        vuescroll: {},
        scrollPanel: {},
        rail: {
          keepShow: true,
        },
        bar: {
          hoverStyle: true,
          onlyShowBarOnScroll: false, // 是否只有滚动的时候才显示滚动条
          background: '#F5F5F5', // 滚动条颜色
          opacity: 0, // 滚动条透明度
          'overflow-x': 'hidden',
        },
      },
      uploadURL: '',
      idStart: 0,
      headers: {
        'Access-Token': localStorage.getItem('token'),
      },
      // 新增的三个弹窗控制变量
      visibleCourse: false,
      visibleQuiz: false,
      visiblePk: false,

      // 新增的三个数据列表
      courseList: [],
      quizList: [],
      pkList: [],

      // 新增的加载状态
      loadingCourse: false,
      loadingQuiz: false,
      loadingPk: false,

      // 新增的分页数据
      quizPageIndex: 1,
      quizPageSize: 10,
      quizTotalPage: 0,

      pkPageIndex: 1,
      pkPageSize: 10,
      pkTotalPage: 0,

      // 新增的列定义
      columnsCourse: [
        { title: '序号', align: 'center', customRender: (text, record, index) => `${index + 1}` },
        { title: '课程名称', dataIndex: 'courseTitle', key: 'courseTitle', align: 'center' },
        { title: '课程类型', dataIndex: 'courseType', key: 'courseType', align: 'center' },
        {
          title: '课程进度',
          dataIndex: 'progress',
          key: 'progress',
          align: 'center',
          customRender: (text) => {
            // text 期望是数字，0-100
            return (
              <a-progress
                percent={Number(text) || 0}
                strokeColor={Number(text) >= 100 ? '#52c41a' : '#1890ff'}
                size="small"
                status={Number(text) >= 100 ? 'success' : 'active'}
                style={{ minWidth: '100px' }}
              />
            );
          },
        },
        {
          title: '认证情况',
          dataIndex: 'isCertified',
          key: 'isCertified',
          align: 'center',
          customRender: (text) => {
            if (text === true || text === 'true' || text === 1) {
              return <a-tag color="green">已认证</a-tag>;
            } else if (text === false || text === 'false' || text === 0) {
              return <a-tag color="red">未认证</a-tag>;
            } else {
              return <a-tag>未知</a-tag>;
            }
          },
        }, ],
      columnsQuiz: [
        { title: '序号', align: 'center', customRender: (text, record, index) => `${index + 1}` },
        { title: '答题时间', dataIndex: 'createTime', key: 'createTime', align: 'center' },
        { title: '答题得分', dataIndex: 'score', key: 'score', align: 'center' },
      ],
      columnsPk: [
        { title: '序号', align: 'center', customRender: (text, record, index) => `${index + 1}` },
        { title: 'PK对手', dataIndex: 'player2Name', key: 'player2Name', align: 'center' },
        { title: 'PK得分', dataIndex: 'player1Points', key: 'player1Points', align: 'center' },
        { title: 'PK时间', dataIndex: 'updateDatetime', key: 'updateDatetime', align: 'center' },
      ],

      currentRecord: null, // 当前操作的用户记录
    };
  },
  watch: {
    visible(newVal, oldVal) {
      if (!newVal) {
        this.restForm('formEdit');
        this.roleAuthList = [];
        this.formEdit.checkedKeys = [];
      }
    },
    visibleKPI(newVal, oldVal) {
      if (!newVal) {
        this.kpiList = [];
      }
    },
    visibleAdd(newVal, oldVal) {
      if (!newVal) {
        this.restForm('form');
        this.form.organizationId = undefined;
        this.form.addList = [];
        this.form.checkedKeys = [];
      }
    },
  },
  mounted() {
    this.columns = document.body.clientWidth <= 1600 ? columnsFixed : columnsNoFixed;
    window.onresize = () =>
      // 屏幕尺寸变化
      (() => {
        this.columns = document.body.clientWidth <= 1600 ? columnsFixed : columnsNoFixed;
      })();

    this.getCompanyAndDeptTree();
    this.uploadURL = `${axios.defaults.baseURL}/user/getUserListByExcel`;
  },
  methods: {
    validatePhone(rule, value, callback) {
      const isMob = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/;
      if (!value) {
        callback(new Error('请输入手机号码'));
      } else if (!isMob.test(value)) {
        callback(new Error('手机号码格式错误'));
      }
      callback();
    },
    validateUserCode(rule, value, callback) {
      const pattern = /^[A-Za-z0-9\-_\u4e00-\u9fa5]+$/;
      if (!value) {
        callback(new Error('请输入用户账号'));
      } else if (!pattern.test(value)) {
        callback(new Error('请输入字母数字、下划线_或中线-或中文'));
      }
      callback();
    },
    /* 刷新组织机构树 */
    refreshOrgTree() {
      this.searchForm.organizationId = '';
      this.selectedKeys = [];
      this.getCompanyAndDeptTree();
    },
    handleChangeUpload(info) {
      if (info.file.status === 'done') {
        const addList = info.file.response.data;
        addList.forEach((item, index) => {
          item.id = this.idStart + index + 1;
        });
        this.form.addList = addList;
        this.idStart = this.form.addList[this.form.addList.length - 1].id;
        this.$message.success('上传成功');
      } else if (info.file.status === 'error') {
        this.$message.error('上传失败');
      }
    },
    addUser() {
      const option = {
        id: this.idStart + 1,
        organization: '',
        userName: '',
        department: '',
        mobilePhone: '',
        userCode: '',
      };
      this.idStart = option.id;
      this.form.addList = [...this.form.addList, option];
    },
    handleChange(value, key, column) {
      const newData = [...this.form.addList];
      const target = newData.find(item => key === item.id);
      if (target) {
        target[column] = value;
        this.form.addList = newData;
      }
    },
    del(key) {
      this.form.addList = this.form.addList.filter(item => key != item.id);
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    /* 启用/禁用 用户 */
    lockedClick(record) {
      const that = this;
      const userName = record.userName;
      const isLocked = record.isLocked;
      const userCode = record.userCode;
      const content = isLocked === '1' ? `确认要禁用\"${userName}\"用户吗？` : `确认要启用\"${userName}\"用户吗？`;
      this.$confirm({
        title: '警告',
        content,
        onOk() {
          req('post', '/user/lockedUser', {
            isLocked: isLocked === '1' ? '0' : '1',
            userCode,
          }).then((res) => {
            if (res.result === 'success') {
              if (isLocked === '1') {
                record.isLocked = '0';
              } else if (isLocked === '0') {
                record.isLocked = '1';
              }
              that.$message.success(res.message);
            }
          });
        },
        onCancel() {
        },
      });
    },
    /* 编辑用户 */
    async editUser(record) {
      this.loading = true;
      // await this.getCompanyAndDeptTree()
      this.loading = false;
      // 单位部门下拉框
      this.createCompanySelect();
      // 查询所有角色
      this.getRoleList();
      this.disabled = true;
      this.title = '修改用户';
      req('post', '/user/getUserWithAuthByCode', {
        userCode: record.userCode,
        roleCode: record.roleCode,
        userRole: record.userRole,
      }).then((res) => {
        this.loading = false;
        if (res.result === 'success') {
          this.visible = true;
          this.$nextTick(() => {
            this.formEdit.userCode = res.data.user_code;
            this.formEdit.userName = res.data.user_name;
            this.formEdit.jobNo = res.data.job_no ? res.data.job_no : '';
            this.formEdit.mobilePhone = res.data.mobile_phone;
            this.formEdit.organizationId = res.data.organization_id;
            this.formEdit.isLocked = res.data.is_locked;
            this.formEdit.userRole = res.data.user_role;
            this.formEdit.isAdmin = res.data.is_admin;
            this.roleAuthList = res.roleAuthList;
            this.formEdit.checkedKeys = res.auths;
          });
        }
      });
    },
    /* 删除用户 */
    removeUser(record) {
      this.loading = true;
      req('post', '/user/removeUser', {
        userCode: record.userCode,
      }).then((res) => {
        this.loading = false;
        if (res.result === 'success') {
          this.$message.success(res.message);
          this.getUserList();
        }
      });
    },
    /* 功能权限树点击复选框触发事件 */
    check(checkedKeys, e) {
      const selectAuth = [];
      if (!checkedKeys || !checkedKeys.length) {
        this.checkedKeys = [];
      }
      checkedKeys.forEach((key, index) => {
        // key包含-
        if ((`${key}`).includes('-')) {
          selectAuth.push(key);
        }
      });
      this.checkedKeys = selectAuth;
    },
    onChangeRole(value, option) {
      req('post', '/user/getMenuAuthByRole', {
        roleId: value,
      }).then((res) => {
        if (res.result === 'success') {
          this.roleAuthList = res.data;
          this.form.checkedKeys = res.authIds;
          this.formEdit.checkedKeys = res.authIds;
        }
      });
    },
    onChange(value, label, extra) {

    },
    async addUsers() {
      this.visibleAdd = true;
      this.title = '批量新增';
      // await this.getCompanyAndDeptTree()
      this.loading = false;
      // 生成单位部门下拉框
      this.createCompanySelect();
      // 生成角色下拉框
      this.getRoleList();
    },
    /* 生成单位部门下拉框 */
    createCompanySelect() {
      const treeData = this.treeData;
      const companyDeptTree = [];
      treeData.forEach((tree, index) => {
        // 单位
        const company = { value: tree.key, label: tree.title, disabled: true };
        const children = [];
        // 部门
        tree.children.forEach((dept, i) => {
          children.push({ value: dept.key, label: dept.title });
        });
        company.children = children;
        companyDeptTree.push(company);
        this.companyDeptTree = companyDeptTree;
      });
    },
    /* 查询所有角色列表 */
    getRoleList() {
      req('post', '/role/getAllRoleList', {})
        .then((res) => {
          if (res.result === 'success') {
            this.roleList = res.data;
            if (this.title !== '修改用户') {
              this.form.userRole = res.userRole;
              this.formEdit.userRole = res.userRole;
              this.roleAuthList = res.authTree;
              this.form.checkedKeys = res.authIds;
              this.formEdit.checkedKeys = res.authIds;
            }
          }
        });
    },
    /* 保存or修改用户信息 */
    submitForm() {
      this.$refs.formEdit.validate((valid) => {
        if (valid) {
          // 处理分配的权限
          const selectAuth = this.formEdit.checkedKeys;
          this.formEdit.selectAuth = JSON.stringify(selectAuth);
          this.submitLoading = true;
          req('post', 'user/updateUserWithAuth', this.formEdit).then((res) => {
            if (res.result === 'success') {
              this.visible = false;
              this.getUserList();
              this.$message.success(res.message);
            }
            this.submitLoading = false;
          });
        }
      });
    },
    submitFormAdd() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const addList = this.form.addList;
          if (addList.length == 0) {
            this.$message.warning('请新增人员');
            return false;
          }
          // 处理分配的权限
          const selectAuth = this.form.checkedKeys;
          this.form.list = JSON.stringify(this.form.addList);
          this.form.selectAuth = JSON.stringify(selectAuth);
          this.submitAddLoading = true;
          req('post', 'user/addUser', {
            organizationId: this.form.organizationId,
            isLocked: this.form.isLocked,
            userRole: this.form.userRole,
            isAdmin: this.form.isAdmin,
            checkedKeys: this.form.checkedKeys,
            list: this.form.list,
            selectAuth: this.form.selectAuth,
          }).then((res) => {
            if (res.result === 'success') {
              this.visibleAdd = false;
              this.getUserList();
              this.$message.success(res.message);
            }
            this.submitAddLoading = false;
          });
        }
      });
    },
    /* 单位部门树 */
    getCompanyAndDeptTree() {
      return new Promise((resolve, reject) => {
        req('post', '/organization/getOrganizationListTree', {})
          .then((res) => {
            if (res.result === 'success') {
              const data = res.data;
              this.treeData = data;
              this.expandedKeys = [data[0].organizationId];
              this.getUserList();
            }
            resolve();
          });
      });
    },
    /* 用户信息列表 */
    getUserList() {
      this.loading = true;
      this.searchForm.page = this.pageIndex;
      this.searchForm.rows = this.pageSize;
      req('post', '/user/getUserListPage', this.searchForm)
        .then((res) => {
          if (res.result === 'success') {
            this.dataList = res.data;
            this.QX = res.QX;
            this.adminVisible = res.adminVisible;
            this.totalPage = res.page.totalResult;
          }
          this.loading = false;
        }).catch((e) => {
          this.loading = false;
        });
    },
    getKpiAttenDance(record) { // KPI考勤
      this.title = 'KPI考勤';
      this.loading = true;
      req('post', '/user/getKpiAttenDance', { userCode: record.userCode })
        .then((res) => {
          this.loading = false;
          if (res.result === 'success') {
            this.visibleKPI = true;
            this.kpiList = res.data;
          }
        });
    },
    // 查询
    getSearch() {
      this.pageIndex = 1;
      this.getUserList();
    },
    /* 重置查询 */
    restSearch(form) {
      this.restForm(form);
      this.searchForm.organizationId = '';
      this.selectedKeys = [];
      this.pageIndex = 1;
      this.getUserList();
    },
    /* 重置表单 */
    restForm(form) {
      this.$refs[form].resetFields();
    },
    /* 改变页数事件 */
    onChangePage(page, pageSize) {
      this.pageIndex = page;
      this.getUserList();
    },
    /* 改变每页显示条数 */
    onShowSizeChange(current, pageSize) {
      this.pageIndex = 1;
      this.pageSize = pageSize;
      this.getUserList();
    },
    /* 点击单位部门树节点触发 */
    onSelect(selectedKeys, info) {
      if (selectedKeys && selectedKeys.length) {
        this.searchForm.organizationId = selectedKeys[0];
        this.selectedKeys = selectedKeys;
        this.getUserList();
      }
    },
    beforeUpload(file) {

    },

    // 查看用户课程信息
    openCourseModal(record) {
      this.currentRecord = record;
      this.loadingCourse = true;
      this.visibleCourse = true;

      req('post', '/course/selectBCourseByUserId', {
        userIdSearch: record.userId, // 使用实际用户ID字段
      }).then((res) => {
        if (res.result === 'success') {
          this.courseList = res.data || [];
        }
        this.loadingCourse = false;
      }).catch(() => {
        this.loadingCourse = false;
      });
    },
    onChangeQuizPage(page, pageSize) {
      this.quizPageIndex = page;
      this.quizPageSize = pageSize;
    },

    // 查看用户PK信息
    openPkModal(record) {
      this.currentRecord = record;
      this.pkPageIndex = 1;
      this.getPkList();
    },

    getPkList() {
      this.loadingPk = true;
      this.visiblePk = true;

      req('post', '/pkRecord/list', {
        userIdSearch: this.currentRecord.userId, // 使用实际用户ID字段
        page: this.pkPageIndex,
        rows: this.pkPageSize,
      }).then((res) => {
        if (res.result === 'success') {
          this.pkList = res.data || [];
          this.pkTotalPage = res.page.totalResult || 0;
        }
        this.loadingPk = false;
      }).catch(() => {
        this.loadingPk = false;
      });
    },

    onChangePkPage(page, pageSize) {
      this.pkPageIndex = page;
      this.pkPageSize = pageSize;
      this.getPkList();
    },
// 导出数据
    exportData(){
      var searchForm = {}
      for (var key in this.searchForm) {
        searchForm[key] = this.searchForm[key]||''
      }
      this.downloading = true
      fileDownload('post', 'home/exportTotalData',searchForm)
        .then(res => {
          this.downloading = false
          this.$message.destroy();
          let blob = new Blob([res]);
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = '统计用户数据.xlsx';
          link.click();
          //释放内存
          window.URL.revokeObjectURL(link.href);
          this.exporting = false;
          this.loading = false;

        }, error => {
          if (error.toString()
            .indexOf('timeout') > 0) {
            this.$message.warning('请求导出超时,数据量过大。');
            this.exporting = false;
            this.loading = false;

          }
        });
    },

  },
};
const columnsFixed = [
  {
    title: '序号',
    align: 'center',
    width: '40px',
    fixed: 'left',
    customRender: (text, record, index) => `${index + 1}`,
  },
  {
    title: '用户账号',
    dataIndex: 'userCode',
    key: 'userCode',
    scopedSlots: { customRender: 'userCode' },
    align: 'center',
    width: 105,
    fixed: 'left',
  },
  {
    title: '用户姓名',
    dataIndex: 'userName',
    key: 'userName',
    scopedSlots: { customRender: 'userName' },
    align: 'center',
    width: 80,
  },
  {
    title: '所在部门',
    dataIndex: 'organizationName',
    key: 'organizationName',
    align: 'center',
    width: 100,
    scopedSlots: { customRender: 'organizationName' },
  },
  {
    title: '所属岗位',
    dataIndex: 'poistionName',
    key: 'poistionName',
    align: 'center',
    width: 100,
    scopedSlots: { customRender: 'poistionName' },
  },
  {
    title: '手机号码',
    dataIndex: 'mobilePhone',
    key: 'mobilePhone',
    scopedSlots: { customRender: 'mobilePhone' },
    align: 'center',
    width: 100,
  },
  {
    title: '账户禁用状态',
    dataIndex: 'isLocked',
    key: 'isLocked',
    align: 'center',
    scopedSlots: { customRender: 'isLocked' },
    width: 95,
  },
  {
    title: '所属角色',
    dataIndex: 'roleName',
    key: 'roleName',
    scopedSlots: { customRender: 'roleName' },
    align: 'center',
    width: 80,
  },
  {
    title: '是否管理员账号',
    dataIndex: 'isAdmin',
    key: 'isAdmin',
    align: 'center',
    width: 105,
    scopedSlots: { customRender: 'isAdmin' },
  },
  {
    title: '最后登录时间',
    dataIndex: 'lastLogin',
    key: 'lastLogin',
    scopedSlots: { customRender: 'lastLogin' },
    align: 'center',
    width: 140,
  },
  {
    align: 'center',
    title: '操作',
    width: 150,
    dataIndex: 'action',
    key: 'action',
    fixed: 'right',
    scopedSlots: { customRender: 'action' },
  },
];
const columnsNoFixed = [
  {
    title: '序号',
    align: 'center',
    width: '40px',
    customRender: (text, record, index) => `${index + 1}`,
  },
  {
    title: '用户账号',
    dataIndex: 'userCode',
    key: 'userCode',
    scopedSlots: { customRender: 'userCode' },
    align: 'center',
    width: 105,
  },
  {
    title: '用户姓名',
    dataIndex: 'userName',
    key: 'userName',
    scopedSlots: { customRender: 'userName' },
    align: 'center',
    width: 80,
  },
  {
    title: '工号',
    dataIndex: 'jobNo',
    key: 'jobNo',
    scopedSlots: { customRender: 'jobNo' },
    align: 'center',
    width: 100,
  },
  {
    title: '所在部门',
    dataIndex: 'organizationName',
    key: 'organizationName',
    align: 'center',
    width: 100,
    scopedSlots: { customRender: 'organizationName' },
  },
  {
    title: '手机号码',
    dataIndex: 'mobilePhone',
    key: 'mobilePhone',
    scopedSlots: { customRender: 'mobilePhone' },
    align: 'center',
    width: 100,
  },
  {
    title: '账户禁用状态',
    dataIndex: 'isLocked',
    key: 'isLocked',
    align: 'center',
    scopedSlots: { customRender: 'isLocked' },
    width: 95,
  },
  {
    title: '所属角色',
    dataIndex: 'roleName',
    key: 'roleName',
    scopedSlots: { customRender: 'roleName' },
    align: 'center',
    width: 80,
  },
  {
    title: '是否管理员账号',
    dataIndex: 'isAdmin',
    key: 'isAdmin',
    align: 'center',
    width: 105,
    scopedSlots: { customRender: 'isAdmin' },
  },
  {
    title: '最后登录时间',
    dataIndex: 'lastLogin',
    key: 'lastLogin',
    scopedSlots: { customRender: 'lastLogin' },
    align: 'center',
    width: 140,
  },
  {
    align: 'center',
    title: '操作',
    width: 154,
    dataIndex: 'action',
    key: 'action',
    fixed: 'right',
    scopedSlots: { customRender: 'action' },
  },
];
const columnsKPI = [
  {
    title: '序号',
    width: '40px',
    align: 'center',
    customRender: (text, row, index) => index + 1,
  },
  {
    title: '所属工序名称',
    align: 'center',
    dataIndex: 'workingProcedureName',
    key: 'workingProcedureName',
    scopedSlots: { customRender: 'workingProcedureName' },
  },
  {
    title: '考勤日期',
    align: 'center',
    dataIndex: 'attendanceDatetime',
    key: 'attendanceDatetime',
    scopedSlots: { customRender: 'attendanceDatetime' },
  },
  {
    title: '当日产量得分',
    align: 'center',
    dataIndex: 'yieldScore',
    key: 'yieldScore',
    scopedSlots: { customRender: 'yieldScore' },
  },
  {
    title: '当日完成数量',
    align: 'center',
    dataIndex: 'yield',
    key: 'yield',
    scopedSlots: { customRender: 'yield' },
  },
  {
    title: '合格率',
    align: 'center',
    dataIndex: 'passrate',
    key: 'passrate',
    scopedSlots: { customRender: 'passrate' },
  },
];
const kpiList = [];
const columnsAdd = [
  {
    title: '序号',
    align: 'center',
    width: '40px',
    customRender: (text, record, index) => `${index + 1}`,
  },
  {
    title: '区县',
    dataIndex: 'organization',
    key: 'organization',
    align: 'center',
    scopedSlots: { customRender: 'organization' },
  },
  {
    title: '部门',
    dataIndex: 'department',
    key: 'department',
    align: 'center',
    scopedSlots: { customRender: 'department' },
  },
  {
    title: '用户姓名',
    dataIndex: 'userName',
    key: 'userName',
    align: 'center',
    scopedSlots: { customRender: 'userName' },
  },
  {
    title: '用户编号',
    dataIndex: 'userCode',
    key: 'userCode',
    align: 'center',
    scopedSlots: { customRender: 'userCode' },
  },
  {
    title: '手机号码',
    dataIndex: 'mobilePhone',
    key: 'mobilePhone',
    align: 'center',
    scopedSlots: { customRender: 'mobilePhone' },
  },
  {
    align: 'center',
    title: '操作',
    width: 130,
    dataIndex: 'action',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  },
];
</script>

<style scoped>
@import "../../../assets/css/maincss.css";
.user {
  display: flex;
  background: none;
  padding: 0 0;
}
.tree {
  min-width: 250px;
  height: 100%;
  padding: 10px;
  background: #fff;
  overflow: auto;
}
.reload {
  position: absolute;
  left: 225px;
  padding: 5px;
  z-index: 9;
}
.user-list {
  width:calc(100% - 250px);
  margin-left: 10px;
  padding: 10px 16px;
  background: #fff;
}

/deep/ .ant-tag-blue .ant-tag-purple{
  margin: 0;
}
.lay-drawer-form {
  width: 1000px;
}


</style>
